package com.platform.common.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.HttpClientConfig;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

public class AliyunSmsUtils {
    /**
     * @param accessKeyId
     * @param secret
     * @param phoneNumber 手机号码
     * @param jsonStr     发送内容
     * @param smsTemplate 模板id
     * @param signName    企业签名
     * @return
     */
    public static String sendSms(String accessKeyId, String secret, String phoneNumber, String jsonStr, String smsTemplate, String signName, boolean isEnable, String proxyIp, String port) {

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, secret);

        if (isEnable) {
            // Client 代理配置
            HttpClientConfig clientConfig = HttpClientConfig.getDefault();
            // 设置HTTP代理
            clientConfig.setHttpProxy("http://" + proxyIp + ":" + port);
            // 设置HTTPS代理
            clientConfig.setHttpsProxy("http://" + proxyIp + ":" + port);
            // 设置忽略代理地址列表
            clientConfig.setNoProxy("127.0.0.1,localhost");
            profile.setHttpClientConfig(clientConfig);
        }

        IAcsClient client = new DefaultAcsClient(profile);

        if (StringUtils.isBlank(phoneNumber) || StringUtils.isBlank(jsonStr) || phoneNumber.length() != 11 || null == smsTemplate) {
            return "{\"Message\":\"参数错误\"}";
        }

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phoneNumber);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", smsTemplate);
        //模板参数，调用方法前拼好json字符串
        request.putQueryParameter("TemplateParam", jsonStr);
        try {
            CommonResponse response = client.getCommonResponse(request);
            return response.getData();
        } catch (ServerException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (ClientException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
